from django.shortcuts import render
import os
from django.http import JsonResponse
from .pgm import Pgm
from .ml import MachineLearn
from .dl import DeepLearn


def index(request):
    return render(request, "face/index.html")


def upload(request):
    if request.method == "POST":
        ret = {"status": False, "data": False, "error": None}
        # f = None
        try:
            img = request.FILES.get("img")  # 取得传递过来的图片
            FILE_PATH = os.path.abspath(os.path.dirname(__file__)) + os.sep + "static" + os.sep + img.name
            # http://127.0.0.1:8000/static/10.pgm
            # FILE_PATH_URL = "/static/" + img.name  # 前端展示图片
            # in_path(FILE_PATH)：  c://ai_project//static//10.pgm
            # out_path： c://ai_project//static//10.pgm.jpg
            OUT_PATH = FILE_PATH + ".jpg"

            #  # http://127.0.0.1:8000/static/10.pgm.jpg
            FILE_PATH_URL = "/static/" + img.name + ".jpg"
            # 上传的图片写入本地
            f = open(FILE_PATH, "wb")
            for chunk in img.chunks(chunk_size=1024 * 1024):
                f.write(chunk)
            ret["status"] = True
            # 将pgm格式的图片保存为jpg格式
            pgm = Pgm()
            # in_path(FILE_PATH)：  c://ai_project//static//10.pgm
            #  out_path： c://ai_project//static//10.pgm.jpg
            pgm.pgm_to_jpg(FILE_PATH, OUT_PATH)  # 保存
        except Exception as e:
            print(e)
            ret["error"] = e
            return JsonResponse({"file_path": "", "file_path_url": "", "status": ret["status"], "error": ret["error"]})
        finally:
            f.close()
        return JsonResponse(
            {"file_path": FILE_PATH, "file_path_url": FILE_PATH_URL, "status": ret["status"], "error": ret["error"]})
def pred(request):
    """人脸识别预测请求"""
    file_path = request.POST.get("file_path", None)

    # 降维的 参数 150--200
    pca = int(request.POST.get("pca", None))
    logic_select = request.POST.get("logic_select", None)
    res_pred = ""
    ml = MachineLearn(pca, file_path)
    if logic_select == "KNN":
        res_pred = ml.knn()
    elif logic_select == "LogicRegression":
        res_pred = ml.logsticRegressor()
    elif logic_select == "DecisionTree":
        res_pred = ml.decisionTree()
    elif logic_select == "DNN":
        dl = DeepLearn(file_path, pca)
        res_pred = dl.keras_DNN()
    return JsonResponse({"msg": res_pred[0], "acc": res_pred[1]})